/*
 * @Author: Hp_lucky 1063512385@qq.com
 * @Date: 2024-08-28 11:36:48
 * @LastEditors: Hp_lucky 1063512385@qq.com
 * @LastEditTime: 2024-09-11 10:18:38
 * @FilePath: \cocos_frame\assets\script\src\Basic\Manager\GameManager.ts
 */
import { Component, Game, _decorator, director, game, Node, SceneAsset, v3, Vec3, UITransform, Tween, tween, Material } from 'cc';
import { LoadingManager } from './LoadingManager';
import { LoadingBundle, SoundCode } from '../Config/BaseEnum';
import { TimeControler as TimeControler } from '../Control/TimeControler';
import { MainModel_Ins } from '../../Game/Main/MainModel';
import { AudioManager } from './AudioManager';
const { ccclass, property } = _decorator;

@ccclass('GameManager')
export class GameManager extends Component {
  static Singleton: GameManager;

  @property(Node)
  mainCamera: Node = null;

  @property(Material)
  grayMaterial: Material;

  static TimeControl: TimeControler = null!;
  static UIController: Node = null!;
  static GameTransform: UITransform = null!;
  static GameManager: { nowTime: number };

  constructor() {
    super();
    GameManager.Singleton = this;
  }

  protected onLoad(): void {
    GameManager.TimeControl = this.node.getComponent(TimeControler)!;
  }

  protected start(): void {
    director.addPersistRootNode(this.node);
    game.on(Game.EVENT_SHOW, this.gameShow, this);
    game.on(Game.EVENT_HIDE, this.gameHide, this);
  }

  async runScene(scene: string) {
    const bundle = LoadingManager.Ins().getBundle(LoadingBundle.SceneBundle);
    const sceneAsset: SceneAsset = await new Promise<SceneAsset>((resolve, reject) => {
      bundle.loadScene(scene, (err, asset) => {
        if (err) {
          reject(err);
        } else {
          resolve(asset);
        }
      });
    });
    this.mainCamera = sceneAsset.scene.getChildByName('Camera');
    sceneAsset.scene.addChild(this.node);
    director.runScene(sceneAsset.scene);
  }

  /** 游戏切回前台 */
  gameShow() {
    // console.log('游戏进入前台');
    // this.playMusic(SoundCode.BGM);
  }

  /** 游戏进入后台 */
  gameHide() {}

  //#region 工具
  getUIWorldPosition(node: Node, out?: Vec3): Vec3 {
    if (!out) out = v3();
    node.getWorldPosition(out);
    const controller = GameManager.UIController;
    out.x -= controller.position.x;
    out.y -= controller.position.y;
    return out;
  }

  converToLocal(worldPos: Vec3) {
    const out = new Vec3();
    const controller = GameManager.UIController;
    out.x = worldPos.x - controller.position.x;
    out.y = worldPos.y - controller.position.y;
    return out;
  }
}
